#include "Topic.h"

#include <sys/stat.h>
#include <sys/types.h>
#include <iostream>

#include "FileSize.h"
#include "recovery/fs/Path.h"
#include "recovery/fs/file/File.h"

using recovery::Status;
using recovery::fs::file::File;

Topic::Topic(const std::string & name, const std::string & root)
: _root(root)
, _directory(recovery::fs::Path::from(root, name))
, _logPath(recovery::fs::Path::from(_directory, name + ".log"))
, _fileSize(std::make_shared<FileSize>())
{
}

int Topic::loadFileSize() {
    File file(_logPath);
    if (!file.touch()) {
        return -1;
    }

    size_t size;
    if (!file.size(size)) {
        return -1;
    }
    _fileSize->set(size);
    return 0;
}

int Topic::open() {
    std::lock_guard<std::mutex> lock(_mutex);
	if(!isOpened()){    
		if(!createIfNotExist(_directory)){
			return -1;
		}
		//TODO: logFileCreate()???
		//TODO: logFileStateLoad() ????
		_opened = true; 
	    return loadFileSize();
	}
    return 0;
};
int Topic::close(){
	if(isOpened()){
		//TODO: flush filesystem
		//TODO: close fs resource
		_opened = false;
	}
	return 0;
}

Status Topic::createIfNotExist(const std::string & dir){
	//TODO: create parent directory for dir
	if(mkdir(dir.c_str(), 0755) != 0){//create failed
		if(errno != EEXIST){
			std::cout << "create failed, and not exist dir, errno:" << errno << ":" << strerror(errno) << std::endl;
			return Status::Failed("create data directory failed");
		}
		else{
			std::cout << "directory:[" << _directory << "]: is exist already" << std::endl;
		}
	}
	else{
		// isDir(
		std::cout << "create directory:[" << _directory << "]:OK" << std::endl;
	}
	return Status::OK();
}
